package com.baimuzhi.live.service;

import com.alibaba.fastjson.JSON;
import com.baimuzhi.live.entity.Live;
import com.baimuzhi.live.entity.LiveConfig;
import com.baimuzhi.live.entity.Res;
import com.baimuzhi.live.utils.ConfigBuild;
import com.baimuzhi.live.utils.ConfigUtil;
import com.baimuzhi.live.utils.HttpUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.MultiValueMap;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName : LiveService
 * @Description :
 * @Author : 肖叶茂
 * @Date: 2023/1/18  16:53
 */
@Service
public class LiveService {



    @Autowired
    private ConfigService configService;

    //创建一个直播间
    public Live createLive(Live live,String serverId) throws UnsupportedEncodingException {
        if(live == null){
            return null;
        }

        if (live.getUserId()==null){
            return null;
        }

        if(live.getLiveConfig() == null){

            LiveConfig liveConfig = configService.getOneById(serverId);
            if(liveConfig == null){
               liveConfig = ConfigUtil.liveConfigs.get(0);
            }
            //默认
            live.setLiveConfig(liveConfig);

        }


        if(live.getId()==null){
            live.setId(String.valueOf(System.currentTimeMillis()));
        }

        LiveConfig liveConfig  =live.getLiveConfig();

        String requestUrl = "http://"+liveConfig.getUrl() + ":" + liveConfig.getHttp() + "/control/get?room=" + live.getId();

        //下面开始请求
        String json = HttpUtil.get(requestUrl, null);
        json = new String(json.getBytes("ISO-8859-1"), "UTF-8");
        Res res = JSON.parseObject(json, Res.class);

        if(res == null||res.getStatus()!=200){
            return null;
        }

        live.setPass(res.getData());

        return live;
    }

}
